package controllers

import (
	"blog-backend/internal/app/dtos"
	"blog-backend/internal/app/models"
	"blog-backend/internal/app/services"
	"blog-backend/internal/utils"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type CommentController struct {
	commentService *services.CommentService
}

func NewCommentController() *CommentController {
	return &CommentController{
		commentService: services.NewCommentService(),
	}
}

// GetComments 获取文章评论
// @Summary 获取文章评论
// @Description 获取指定文章的所有评论
// @Tags 评论
// @Produce json
// @Param id path int true "文章ID"
// @Success 200 {object} dtos.SuccessResponse{data=dtos.CommentListResponse} "获取成功"
// @Failure 400 {object} dtos.ErrorResponse "无效的文章ID"
// @Failure 404 {object} dtos.ErrorResponse "文章不存在"
// @Failure 500 {object} dtos.ErrorResponse "服务器内部错误"
// @Router /api/posts/{id}/comments [get]
func (c *CommentController) GetComments(ctx *gin.Context) {
	postID, err := strconv.ParseUint(ctx.Param("id"), 10, 32)
	if err != nil {
		utils.RespondError(ctx, http.StatusBadRequest, "无效的文章ID")
		return
	}

	comments, err := c.commentService.GetCommentsByPost(uint(postID))
	if err != nil {
		utils.RespondError(ctx, http.StatusNotFound, "文章不存在")
		return
	}

	// 构建响应DTO
	var commentResponses []dtos.CommentResponse
	for _, comment := range comments {
		commentResponses = append(commentResponses, c.buildCommentResponse(&comment))
	}

	utils.RespondJSON(ctx, http.StatusOK, dtos.SuccessResponse{
		Success: true,
		Message: "获取评论成功",
		Data: dtos.CommentListResponse{
			Comments: commentResponses,
			Total:    len(commentResponses),
		},
	})
}

// CreateComment 创建评论
// @Summary 创建评论
// @Description 为指定文章创建评论
// @Tags 评论
// @Accept json
// @Produce json
// @Param id path int true "文章ID"
// @Param comment body dtos.CreateCommentDto true "评论内容"
// @Success 201 {object} dtos.SuccessResponse{data=dtos.CommentResponse} "创建成功"
// @Failure 400 {object} dtos.ErrorResponse "请求参数错误"
// @Failure 404 {object} dtos.ErrorResponse "文章不存在"
// @Failure 500 {object} dtos.ErrorResponse "服务器内部错误"
// @Router /api/posts/{id}/comments [post]
func (c *CommentController) CreateComment(ctx *gin.Context) {
	postID, err := strconv.ParseUint(ctx.Param("id"), 10, 32)
	if err != nil {
		utils.RespondError(ctx, http.StatusBadRequest, "无效的文章ID")
		return
	}

	var dto dtos.CreateCommentDto
	if err := ctx.ShouldBindJSON(&dto); err != nil {
		utils.RespondError(ctx, http.StatusBadRequest, err.Error())
		return
	}

	// 尝试从上下文中获取用户ID
	var userID uint
	if id, exists := ctx.Get("userID"); exists {
		userID = id.(uint)
	}

	comment, err := c.commentService.CreateComment(uint(postID), userID, dto)
	if err != nil {
		utils.RespondError(ctx, http.StatusInternalServerError, err.Error())
		return
	}

	utils.RespondJSON(ctx, http.StatusCreated, dtos.SuccessResponse{
		Success: true,
		Message: "评论创建成功",
		Data:    c.buildCommentResponse(comment),
	})
}

// DeleteComment 删除评论
// @Summary 删除评论
// @Description 删除指定评论
// @Tags 评论
// @Produce json
// @Security Bearer
// @Param id path int true "评论ID"
// @Success 200 {object} dtos.SuccessResponse "删除成功"
// @Failure 400 {object} dtos.ErrorResponse "无效的评论ID"
// @Failure 401 {object} dtos.ErrorResponse "未认证"
// @Failure 403 {object} dtos.ErrorResponse "无权删除此评论"
// @Failure 404 {object} dtos.ErrorResponse "评论不存在"
// @Failure 500 {object} dtos.ErrorResponse "服务器内部错误"
// @Router /api/comments/{id} [delete]
func (c *CommentController) DeleteComment(ctx *gin.Context) {
	commentID, err := strconv.ParseUint(ctx.Param("id"), 10, 32)
	if err != nil {
		utils.RespondError(ctx, http.StatusBadRequest, "无效的评论ID")
		return
	}

	userID := ctx.MustGet("userID").(uint)

	if err := c.commentService.DeleteComment(uint(commentID), userID); err != nil {
		status := http.StatusInternalServerError
		if err.Error() == "无权删除此评论" {
			status = http.StatusForbidden
		} else if err.Error() == "评论不存在" {
			status = http.StatusNotFound
		}
		utils.RespondError(ctx, status, err.Error())
		return
	}

	utils.RespondJSON(ctx, http.StatusOK, dtos.SuccessResponse{
		Success: true,
		Message: "删除评论成功",
	})
}

// buildCommentResponse 构建评论响应DTO
func (c *CommentController) buildCommentResponse(comment *models.Comment) dtos.CommentResponse {
	response := dtos.CommentResponse{
		ID:        comment.ID,
		Content:   comment.Content,
		CreatedAt: comment.CreatedAt,
	}

	// 设置作者信息
	if comment.UserID != nil {
		response.User = &dtos.UserInfo{
			ID:       comment.User.ID,
			Username: comment.User.Username,
			Avatar:   comment.User.Avatar,
		}
	} else {
		response.Author = comment.Author
	}

	// 递归构建回复评论
	for _, reply := range comment.Replies {
		response.Replies = append(response.Replies, c.buildCommentResponse(&reply))
	}

	return response
}